package com.achao.thread;

import com.achao.dto.Request;
import com.achao.dto.Response;
import com.achao.factory.ServletFactory;
import com.achao.utils.ParamUtils;

import java.io.*;
import java.net.Socket;

/**
 * @Author: achao
 * @DateTime: 2022/8/9 19:55
 * @Description: TODO
 */
public class ReadThread implements Runnable {

    private Socket socket;

    public ReadThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String line;
        String reqMessage = "";
        try {
            while ((line = br.readLine()) != null && line.length() > 0) {
                reqMessage += line + "\n";
            }
            System.out.println("=====================请求报文======================");
            System.out.println(reqMessage);
            System.out.println("==================================================");

            String method = reqMessage.split("\r")[0].split("/")[0].trim().toLowerCase();
            System.out.println("请求的方法是: "+method);

            String resourcePath = "/"+reqMessage.split("\r")[0].split("/")[1].split(" ")[0];
            System.out.println("资源路径是: "+resourcePath);

            /*由于只是简易版,就不获取字符编码那些其他信息了...*/

            if (resourcePath.equals("/")){
                OutputStream out = socket.getOutputStream();
                PrintWriter pw = new PrintWriter(out);
                pw.println(ParamUtils.RESP_PROTOCOL+ParamUtils.SUCCESS_CODE);
                pw.println(ParamUtils.RESP_PROTOCOL+ParamUtils.SUCCESS_CODE);
                pw.println(ParamUtils.CONTENT_TYPE+ParamUtils.UTF8);
                pw.println();
                pw.println("你好！世界");
                pw.println("<br/><h1 style='color:red'>Hello World！</h1>");
                pw.flush();

                // 关闭资源
                pw.close();
                out.close();
                br.close();
                socket.close();
            }else if(resourcePath.equals("/favicon.ico")) {
                System.out.println("你个不要脸的/favicon.ico,看我拦截你!!!");
            }else{
                Request req = new Request(method, resourcePath);
                Response resp = new Response(socket.getOutputStream());
                try {
                    ServletFactory.getBean(req,resp);
                }catch (Exception e){
                    System.out.println(e);
                    resp.write("404找不到页面");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
